package org.linlinjava.litemall.wx.service.impl;

import org.linlinjava.litemall.db.domain.UserAccountBinding;
import org.linlinjava.litemall.db.service.UserAccountBindingService;
import org.linlinjava.litemall.wx.service.WxUserAccountBindingService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class WxUserAccountBindingServiceImpl implements WxUserAccountBindingService {
    
    private static final Logger logger = LoggerFactory.getLogger(WxUserAccountBindingServiceImpl.class);
    
    @Resource
    private UserAccountBindingService userAccountBindingService;

    @Override
    @Transactional
    public UserAccountBinding createBinding(Integer litemallUserId, String amspUserCode, Integer amspUserId) {
        logger.info("创建绑定关系，用户ID: {}, AMSP用户代码: {}, AMSP用户ID: {}", 
                   litemallUserId, amspUserCode, amspUserId);
        
        if (litemallUserId == null || StringUtils.isEmpty(amspUserCode)) {
            logger.warn("参数不完整，用户ID: {}, AMSP用户代码: {}, AMSP用户ID: {}", 
                       litemallUserId, amspUserCode, amspUserId);
            return null;
        }
        
        try {
            // 检查AMSP账号是否可以被当前用户绑定
            if (!userAccountBindingService.canAmspAccountBindToUser(amspUserCode, litemallUserId)) {
                Integer boundUserId = userAccountBindingService.getAmspAccountBoundUserId(amspUserCode);
                logger.warn("AMSP账号 {} 已被用户 {} 绑定，无法为用户 {} 创建绑定", 
                           amspUserCode, boundUserId, litemallUserId);
                throw new RuntimeException("AMSP账号已被其他用户绑定");
            }
            
            return userAccountBindingService.createBinding(litemallUserId, amspUserCode, amspUserId);
        } catch (RuntimeException e) {
            logger.error("创建绑定关系失败: {}", e.getMessage());
            throw e; // 重新抛出业务异常
        } catch (Exception e) {
            logger.error("创建绑定关系失败", e);
            throw new RuntimeException("系统错误，创建绑定关系失败");
        }
    }

    @Override
    @Transactional
    public boolean unbindAccount(Integer litemallUserId, String amspUserCode) {
        logger.info("解绑账户，用户ID: {}, AMSP用户代码: {}", litemallUserId, amspUserCode);
        
        if (litemallUserId == null || StringUtils.isEmpty(amspUserCode)) {
            logger.warn("参数不完整");
            return false;
        }
        
        try {
            UserAccountBinding binding = userAccountBindingService.findByLitemallUserIdAndAmspUserCode(
                litemallUserId, amspUserCode);
            if (binding == null) {
                logger.warn("绑定关系不存在");
                return false;
            }
            
            return userAccountBindingService.unbindAccount(binding.getId()) > 0;
        } catch (Exception e) {
            logger.error("解绑账户失败", e);
            return false;
        }
    }

    @Override
    public List<UserAccountBinding> getUserBindings(Integer litemallUserId) {
        logger.info("查询用户绑定列表，用户ID: {}", litemallUserId);
        
        if (litemallUserId == null) {
            logger.warn("用户ID为空");
            return null;
        }
        
        try {
            return userAccountBindingService.queryByLitemallUserId(litemallUserId);
        } catch (Exception e) {
            logger.error("查询用户绑定列表失败", e);
            return null;
        }
    }

    @Override
    public UserAccountBinding getPrimaryBinding(Integer litemallUserId) {
        logger.info("查询用户主要绑定，用户ID: {}", litemallUserId);
        
        if (litemallUserId == null) {
            logger.warn("用户ID为空");
            return null;
        }
        
        try {
            return userAccountBindingService.getPrimaryBinding(litemallUserId);
        } catch (Exception e) {
            logger.error("查询用户主要绑定失败", e);
            return null;
        }
    }

    @Override
    public boolean isBound(Integer litemallUserId, String amspUserCode) {
        logger.info("检查绑定状态，用户ID: {}, AMSP用户代码: {}", litemallUserId, amspUserCode);
        
        if (litemallUserId == null || StringUtils.isEmpty(amspUserCode)) {
            logger.warn("参数不完整");
            return false;
        }
        
        try {
            return userAccountBindingService.isBound(litemallUserId, amspUserCode);
        } catch (Exception e) {
            logger.error("检查绑定状态失败", e);
            return false;
        }
    }

    @Override
    public boolean isBindingExists(Integer litemallUserId, String amspUserCode) {
        logger.info("检查绑定关系是否存在，用户ID: {}, AMSP用户代码: {}", litemallUserId, amspUserCode);
        
        if (litemallUserId == null || StringUtils.isEmpty(amspUserCode)) {
            logger.warn("参数不完整");
            return false;
        }
        
        try {
            return userAccountBindingService.isBindingExists(litemallUserId, amspUserCode);
        } catch (Exception e) {
            logger.error("检查绑定关系失败", e);
            return false;
        }
    }

    @Override
    public UserAccountBinding getBindingByAmspUserCode(String amspUserCode) {
        logger.info("根据AMSP用户代码查询绑定关系: {}", amspUserCode);
        
        if (StringUtils.isEmpty(amspUserCode)) {
            logger.warn("AMSP用户代码为空");
            return null;
        }
        
        try {
            return userAccountBindingService.findActiveBoundByAmspUserCode(amspUserCode);
        } catch (Exception e) {
            logger.error("根据AMSP用户代码查询绑定关系失败", e);
            return null;
        }
    }

    @Override
    public boolean isAmspAccountBound(String amspUserCode) {
        logger.info("检查AMSP账号是否已被绑定: {}", amspUserCode);
        
        if (StringUtils.isEmpty(amspUserCode)) {
            logger.warn("AMSP用户代码为空");
            return false;
        }
        
        try {
            return userAccountBindingService.isAmspAccountBound(amspUserCode);
        } catch (Exception e) {
            logger.error("检查AMSP账号绑定状态失败", e);
            return false;
        }
    }

    @Override
    public boolean canAmspAccountBindToUser(String amspUserCode, Integer litemallUserId) {
        logger.info("检查AMSP账号是否可以被用户绑定: {} -> {}", amspUserCode, litemallUserId);
        
        if (StringUtils.isEmpty(amspUserCode) || litemallUserId == null) {
            logger.warn("参数不完整");
            return false;
        }
        
        try {
            return userAccountBindingService.canAmspAccountBindToUser(amspUserCode, litemallUserId);
        } catch (Exception e) {
            logger.error("检查AMSP账号绑定可行性失败", e);
            return false;
        }
    }

    @Override
    public Integer getAmspAccountBoundUserId(String amspUserCode) {
        logger.info("获取AMSP账号绑定的用户ID: {}", amspUserCode);
        
        if (StringUtils.isEmpty(amspUserCode)) {
            logger.warn("AMSP用户代码为空");
            return null;
        }
        
        try {
            return userAccountBindingService.getAmspAccountBoundUserId(amspUserCode);
        } catch (Exception e) {
            logger.error("获取AMSP账号绑定用户失败", e);
            return null;
        }
    }
} 